<template>
  <el-drawer
    :model-value="checkDialog"
    @close="$emit('assign-dialog')"
    size="80%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
  >
    <template #header>
      <div class="header">
        <div class="text">配件详情</div>
      </div>
    </template>
    <div v-loading="loading" element-loading-text="加载中...">
      <h4 class="title_top">基本信息</h4>
      <div class="table-detail">
        <div v-if="detailData" class="basic_info">
          <div class="info_item">
            <div class="label">申请编码:</div>
            <div class="value">{{ detailData.code }}</div>
          </div>
          <div class="info_item">
            <div class="label">申请时间:</div>
            <div class="value">{{ detailData.createTime }}</div>
          </div>
          <div class="info_item">
            <div class="label">费用状态:</div>
            <div class="value">
              <HStatus :height="22" type="warning" v-if="detailData.status === 1">待审核</HStatus>
              <HStatus :height="22" type="success" v-if="detailData.status === 2">已通过</HStatus>
              <HStatus :height="22" type="error" v-if="detailData.status === 3">已驳回</HStatus>
            </div>
          </div>
          <div class="info_item">
            <div class="label">申请类型:</div>
            <div class="value">
              <div v-if="detailData.type === 1">平台配件</div>
              <div v-else-if="detailData.type === 2" style="display: flex; gap: 5px">
                <span>外部配件</span>
                <span>-</span>
                <span v-if="detailData.networkSpareType === 1">服务商配件</span>
                <span v-else-if="detailData.networkSpareType === 2">工程师配件</span>
                <span v-else>自购配件</span>
              </div>
            </div>
          </div>
          <div class="info_item">
            <div class="label">审批时间:</div>
            <div class="value">{{ detailData.reviewTime }}</div>
          </div>
          <div class="info_item">
            <div class="label">关联工单:</div>
            <div class="value">{{ detailData.workNo }}</div>
          </div>

          <div class="info_item label_top_item">
            <div class="label">申请人员:</div>
            <div class="value">{{ detailData.applyEmp }}</div>
          </div>

          <div class="info_item label_top_item">
            <div class="label">申批人员:</div>
            <div class="value">{{ detailData.reviewEmp }}</div>
          </div>
          <div class="info_item label_top_item">
            <div class="label">配件收货地址:</div>
            <div class="value">
              {{ detailData.receiptName }} &nbsp;{{ detailData.receiptPhone }}&nbsp;{{
                detailData.receiptProvince
              }}{{ detailData.receiptCity }}{{ detailData.receiptArea }}{{ detailData.receiptTown
              }}{{ detailData.receiptAddress }}
            </div>
          </div>
        </div>
      </div>
      <h4 v-if="detailData?.oldCopeWay" class="title_top">旧件信息</h4>
      <div v-if="detailData?.oldCopeWay" class="table-detail">
        <el-form v-if="detailData" class="old_part_detail">
          <div class="dis_f">
            <el-form-item label="旧件处理:">{{
              options7[detailData.oldCopeWay - 1]?.name
            }}</el-form-item>
            <el-form-item v-if="detailData.oldCopeWay == 2" label="旧件收货信息:"
              >{{ detailData.oldReceiptName }} &nbsp;{{ detailData.oldReceiptPhone }}&nbsp;{{
                detailData.oldReceiptProvince
              }}{{ detailData.oldReceiptCity }}{{ detailData.oldReceiptArea
              }}{{ detailData.oldReceiptTown }}{{ detailData.oldReceiptAddress }}
            </el-form-item>
          </div>
          <el-form-item v-if="detailData.oldCopeWay == 2" class="mag-l" label="退回仓库:">{{
            detailData.store
          }}</el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="activeName" class="table-detail" @tab-change="handleTabChange">
        <el-tab-pane label="配件物料" name="first">
          <el-table
            :border="true"
            :data="feeDetails"
            max-height="350px"
            resizable
            stripe
            v-loading="getOrderSpareMaterialListLoading"
          >
            <template #empty>
              <el-empty :image-size="60" description="暂无数据" />
            </template>
            <!--序号-->
            <el-table-column
              align="center"
              fixed="left"
              label="序号"
              min-width="50"
              show-overflow-tooltip
              type="index"
            />

            <!--审核状态-->
            <el-table-column label="审核状态" prop="name" show-overflow-tooltip width="80">
              <template #default="scope">
                <HStatus :height="22" type="warning" v-if="scope.row.status === 1">待审核</HStatus>
                <HStatus :height="22" type="success" v-if="scope.row.status === 2">已通过</HStatus>
                <HStatus :height="22" type="error" v-if="scope.row.status === 3">已驳回</HStatus>
              </template>
            </el-table-column>

            <!--收支类型-->
            <el-table-column label="收支类型" prop="date" show-overflow-tooltip width="100">
              <template #default="scope">
                <span v-if="scope.row.type === 1">商家承担</span>
                <span v-else>平台承担</span>
              </template>
            </el-table-column>

            <!--申请的物料-->
            <el-table-column label="申请的物料" prop="name" show-overflow-tooltip width="180">
              <template v-slot="i">
                <span>{{
                  `${i.row.applySpareModel} ${i.row.applySpareSpec} ${i.row.applySpareSpecCode}`
                }}</span>
              </template>
            </el-table-column>

            <!--审核后的物料-->
            <el-table-column label="审核后的物料" prop="name" show-overflow-tooltip width="180">
              <template #default="scope">
                <span
                  v-if="
                    scope.row.checkSpareModel ||
                    scope.row.checkSpareSpec ||
                    scope.row.checkSpareSpecCode
                  "
                  >{{
                    `${scope.row.checkSpareModel} ${scope.row.checkSpareSpec} ${scope.row.checkSpareSpecCode}`
                  }}</span
                >
                <span></span>
              </template>
            </el-table-column>

            <!--数量-->
            <el-table-column
              align="center"
              label="数量"
              prop="qty"
              show-overflow-tooltip
              width="80"
            />

            <!--平台承担费用-->
            <el-table-column
              align="center"
              label="平台承担费用"
              prop="price"
              show-overflow-tooltip
              width="120"
            >
              <template #default="scope"> ￥{{ scope.row.price.toFixed(2) }} </template>
            </el-table-column>

            <!--向服务商支付费用-->
            <el-table-column
              align="center"
              label="向服务商支付费用"
              prop="payNetworkPrice"
              show-overflow-tooltip
              width="140"
            >
              <template #default="scope"> ￥{{ scope.row.payNetworkPrice.toFixed(2) }} </template>
            </el-table-column>

            <!--收取商家费用-->
            <el-table-column
              align="center"
              label="收取商家费用"
              prop="receiveFactoryPrice"
              show-overflow-tooltip
              width="140"
            >
              <template #default="scope">
                ￥{{ scope.row.receiveFactoryPrice.toFixed(2) }}
              </template>
            </el-table-column>

            <!--出库仓库-->
            <el-table-column label="出库仓库" prop="store" show-overflow-tooltip width="120" />

            <!--备注-->
            <el-table-column label="备注" prop="remark" show-overflow-tooltip width="170" />

            <!--附件-->
            <el-table-column label="附件" prop="city" width="460">
              <template v-slot="scope">
                <div style="display: flex; align-items: center; gap: 8px">
                  <div v-for="(img, imgIndex) in scope.row.images" :key="img.id">
                    <el-image
                      style="width: 40px; height: 40px"
                      :src="img.image"
                      :preview-src-list="scope.row.images.map((item) => item.image)"
                      :initial-index="imgIndex"
                      fit="contain"
                      :max-scale="15"
                      preview-teleported
                    />
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="出库记录" name="second">
          <el-table :border="true" :data="tableData2" height="300px" resizable stripe>
            <template #empty>
              <el-empty :image-size="60" description="暂无数据" />
            </template>
            <!--状态-->
            <el-table-column label="状态" prop="name" show-overflow-tooltip width="200" />

            <!--单据编码-->
            <el-table-column label="单据编码" prop="date" show-overflow-tooltip width="120" />

            <!--收付类型-->
            <el-table-column label="收付类型" prop="date" show-overflow-tooltip width="100" />

            <!--总金额-->
            <el-table-column label="总金额" prop="city" show-overflow-tooltip width="120" />

            <!--结算方-->
            <el-table-column label="结算方" prop="state" show-overflow-tooltip width="100" />

            <!--结算时间-->
            <el-table-column label="结算时间" prop="city" show-overflow-tooltip width="170" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="操作日志" name="third">
          <el-table :border="true" :data="detailDataLog" max-height="350px" resizable stripe>
            <template #empty>
              <el-empty :image-size="60" description="暂无数据" />
            </template>
            <!--序号-->
            <el-table-column align="center" fixed="left" label="序号" type="index" width="50" />

            <!--操作人-->
            <el-table-column label="操作人" prop="createEmp" show-overflow-tooltip width="140" />

            <!--操作事件-->
            <el-table-column label="操作事件" prop="event" show-overflow-tooltip width="240" />

            <!--备注-->
            <el-table-column label="备注" min-width="220" prop="content" show-overflow-tooltip />

            <!--时间-->
            <el-table-column label="时间" prop="createTime" width="150" />
          </el-table>
          <div class="pagination">
            <Pagination
              ref="pagination"
              :list_total="totalList"
              @size-change="getOrderSpareLogList()"
              @current-change="getOrderSpareLogList()"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <HButton isModal @click="$emit('assign-dialog')">关闭</HButton>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, toRefs, watch } from 'vue'
  import {
    getOrderSpareMaterial,
    OrderSpareDetailProjectInfo,
    OrderSpareLogList,
  } from '@/api/parts'
  import Pagination from '@/components/Pagination/index.vue'
  import { ElMessage } from 'element-plus'
  import { OperationLog, OrderPartsDetail, PartsMaterial } from './types'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'

  const props = defineProps({
    checkDialog: Boolean,
    partsId: String,
    workNo: String,
    feeNo: String,
  })

  const emits = defineEmits<{
    (e: 'assign-dialog'): void
    (e: 'update-list'): void
  }>()

  const { checkDialog, partsId } = toRefs(props)
  const loading = ref(false)
  const tableData2 = []

  // 工单配件详情
  const detailData = ref<OrderPartsDetail | null>(null)

  // 操作日志列表
  const detailDataLog = ref<Array<OperationLog>>([])

  // 操作日志列表总条数
  const totalList = ref(0)

  // 当前选中的标签
  const activeName = ref('first')

  // 配件物料列表
  const feeDetails = ref<Array<PartsMaterial>>([])

  // 操作日志分页组件实例
  const pagination = ref<InstanceType<typeof Pagination> | null>(null)

  const options = [
    { value: 1, name: '待审核' },
    { value: 2, name: '已通过' },
    { value: 3, name: '已驳回' },
  ]
  const options7 = [
    { name: '废弃', value: 1 },
    { name: '旧件退回', value: 2 },
  ]
  const options6 = [
    { name: '平台配件', value: 1 },
    { name: '服务商配件', value: 2 },
  ]

  /**
   * 根据工单配件ID获取工单配件详情
   * @param {string} id 工单配件ID
   */
  const getOrderSpareDetailProjectInfo = async (id: string) => {
    loading.value = true
    const res = await OrderSpareDetailProjectInfo(id)
    if (res.data.success) {
      detailData.value = res.data.data.row
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 4000,
          offset: 200,
          type: 'error',
        })
    }
    loading.value = false
  }

  /**
   * 获取工单配件日志列表
   */
  const getOrderSpareLogList = async () => {
    loading.value = true
    let data = {
      limit: 50,
      page: 1,
    }
    if (pagination.value) {
      data.limit = pagination.value.size
      data.page = pagination.value.current
    }
    const res = await OrderSpareLogList(data, partsId.value)
    if (res.data.success) {
      detailDataLog.value = res.data.data.rows
      totalList.value = Number(res.data.data.total)
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 4000,
          offset: 200,
          type: 'error',
        })
    }
    loading.value = false
  }

  // 根据工单配件ID获取工单配件详情的物料信息加载
  const getOrderSpareMaterialListLoading = ref(false)

  /**
   * 根据工单配件ID获取工单配件详情的物料信息
   * @param {string} id 工单配件ID
   */
  const getOrderSpareMaterialList = async (id: string) => {
    getOrderSpareMaterialListLoading.value = true
    const res = await getOrderSpareMaterial(id)
    getOrderSpareMaterialListLoading.value = false
    if (res.data.success) {
      feeDetails.value = res.data.data.rows
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 4000,
          offset: 200,
          type: 'error',
        })
    }
  }

  /**
   * tab标签切换事件
   * @param {string} val 标签名
   */
  const handleTabChange = (val: string) => {
    switch (val) {
      case 'first':
        getOrderSpareMaterialList(partsId.value)
        break
      case 'second':
        break
      case 'third':
        getOrderSpareLogList()
        break
    }
  }

  watch(
    props,
    async (value) => {
      if (value.partsId && value.checkDialog) {
        await getOrderSpareDetailProjectInfo(value.partsId)
        await getOrderSpareMaterialList(value.partsId)
      }
    },
    { immediate: true },
  )
</script>
<style lang="scss" scoped>
  .header {
    .text {
      font-size: 16px;
      color: #000;
    }
  }

  .title_top {
    border-left: 2px solid #007cff;
    line-height: 14px;
    padding-left: 6px;
  }

  .basic_info {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    row-gap: 6px;
    padding-left: 24px;
    margin: 26px 0 12px 0;

    .info_item {
      display: flex;
      gap: 5px;
      align-items: center;

      .label {
        white-space: nowrap;
        color: $formLabelColor;
      }
    }

    .label_top_item {
      align-items: flex-start !important;
    }
  }

  :deep(.old_part_detail) {
    display: flex;
    gap: 12px;

    .dis_f {
      display: flex;
      flex-direction: column;

      .mag-l {
        margin-left: 200px;
      }
    }

    .el-form-item__label {
      color: #999;
      font-size: 12px;
    }

    .el-form-item__content {
      font-size: 12px;
      height: fit-content;
    }
  }

  .pagination {
    margin-top: 8px;
  }

  .footer_btn {
    display: flex;
    justify-content: end;
    align-items: center;
    margin-right: 8px;
  }

  .disf_ipc {
    display: flex;

    p {
      width: 40px;
      height: 40px;
      margin-right: 6px;
      border: 1px solid #7f7f7f27;
      border-radius: 2px;
      box-sizing: border-box;

      .img {
        width: 100%;
        border-radius: 2px;
        cursor: pointer;
      }
    }
  }

  .coloe {
    margin-top: 10px;
    text-align: right;
  }

  .pagination {
    height: 42px;
    display: flex;
    justify-content: flex-end;
  }

  @import '../index.scss';
</style>
